package json;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

/**
 * JSONStringer可以用来快速构建一个JSON格式的文本，并转换成String，可以写入文件；
 * JSONStringer是JSONWriter的子类;
 * JSONStringer一般通过object().key().value().key().value().endObject()进行构造;
 * object()表明开始一个对象，即添加｛  ;
 * endObject()表明结束一个对象，即添加 ｝ ;
 * array()表明开始一个数组,即添加一个 [ ;
 * endArray()表明结束一个数组，即添加一个 ] ;
 * key()表示添加一个key;
 * value()表示添加一个value;
 * @author Administrator
 *
 */
public class JsonStringerDemo {
	public static void main(String[] args) throws JSONException, IOException {
		JSONStringer js = new JSONStringer();  
        JSONObject obj2 = new JSONObject();  
        JSONObject obj3 = new JSONObject();  
        JSONObject obj4 = new JSONObject();  
        obj4.put("title", "book1").put("price", "$11");  
        obj3.put("book", obj4);  
        obj3.put("author", new JSONObject().put("name", "author-1"));  
          
        JSONObject obj5 = new JSONObject();  
        JSONObject obj6 = new JSONObject();  
        obj6.put("title", "book2").put("price", "$22");  
        obj5.put("book", obj6);  
        obj5.put("author", new JSONObject().put("name", "author-2"));  
          
        JSONArray obj7 = new JSONArray();  
        obj7.put(obj3).put(obj5);  
          
          
          
        obj2.put("title","BOOK");  
        obj2.put("signing", obj7);  
          
        js.object().key("session").value(obj2).endObject();  
          
        System.out.println(js.toString());  
        PrintWriter out = new PrintWriter(new FileOutputStream("1.txt"));  
        out.println(js.toString()); 
        out.close();
		
	}
	
	/***
	 * {"session":
				{
				"title":"BOOK",
				"signing":[
				{
					"author":
					{
						"name":"author-1"
					},
					"book":
					{
						"title":"book1",
						"price":"$11"
					}
				},
				{
					"author":
					{
						"name":"author-2"
					},
					"book":
					{
						"title":"book2",
						"price":"$22"
					}
				}
				]}
		}
	 */
}
